using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using System.Threading;

namespace AstroX
{
    public class PowerControl
    {
        OutputPort p = new OutputPort(AstoXPinMap.PowerPin, false);
        //WaterSensor s;
        Timer shutdownTimer;
        Timer poweroffTimer;

        public PowerControl()
        {
            //s = new WaterSensor();
            
            FlightControl.FlightPhaseChanged += new FlightPhaseChangeHandler(FlightControl_FlightPhaseChanged);
        }

        void FlightControl_FlightPhaseChanged(FlightPhases newphase)
        {
            if (newphase == FlightPhases.Ascent)
            {
                Program.Print("Switching power on");
                p.Write(true);//turn on back up power
                shutdownTimer = new Timer(TimeOut, this, 1000 * FlightControl.FlightTime, 1000 * FlightControl.FlightTime);
            }
        }

        public void ShutDown()
        {
            shutdownTimer.Dispose();
            Program.Print("Shut the system down");
            FlightControl.CurrentPhase = FlightPhases.Shutdown;
            poweroffTimer = new Timer(PowerOff, null, FlightControl.ShutDownTime, 0);
            
            
        }

        public void PowerOff(object state)
        {
            poweroffTimer.Dispose();
            Program.Print("Powering down");
            p.Write(false);
            
            
        }

        void TimeOut(object state)
        {
            ShutDown();
//TODO: Add water detection
            //if (s.IsWaterPresent)
            //{
            //    ShutDown();
            //}
            //else
            //{
            //    s.WaterDetected += new WaterDetectedHandler(s_WaterDetected);
            //}
        }

        void s_WaterDetected()
        {
            FlightControl.CurrentPhase = FlightPhases.Shutdown;
        }
    }
}
